//
//  UIControl+STBlock.m
//  STFramework
//
//  Created by jerry on 2019/5/2.
//  Copyright © 2019 jerry. All rights reserved.
//

#import "UIControl+STBlock.h"
#import <objc/runtime.h>

#define ST_UICONTROL_EVENT(methodName, eventName)                                \
-(void)methodName : (void (^)(void))eventBlock {                              \
objc_setAssociatedObject(self, @selector(methodName:), eventBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);\
[self addTarget:self                                                        \
action:@selector(methodName##Action:)                                       \
forControlEvents:UIControlEvent##eventName];                                \
}                                                                               \
-(void)methodName##Action:(id)sender {                                        \
void (^block)(void) = objc_getAssociatedObject(self, @selector(methodName:));  \
if (block) {                                                                \
block();                                                                \
}                                                                           \
}

@interface UIControl ()

@end
@implementation UIControl (STBlock)

ST_UICONTROL_EVENT(st_touchDown, TouchDown)
ST_UICONTROL_EVENT(st_touchDownRepeat, TouchDownRepeat)
ST_UICONTROL_EVENT(st_touchDragInside, TouchDragInside)
ST_UICONTROL_EVENT(st_touchDragOutside, TouchDragOutside)
ST_UICONTROL_EVENT(st_touchDragEnter, TouchDragEnter)
ST_UICONTROL_EVENT(st_touchDragExit, TouchDragExit)
ST_UICONTROL_EVENT(st_touchUpInside, TouchUpInside)
ST_UICONTROL_EVENT(st_touchUpOutside, TouchUpOutside)
ST_UICONTROL_EVENT(st_touchCancel, TouchCancel)
ST_UICONTROL_EVENT(st_valueChanged, ValueChanged)
ST_UICONTROL_EVENT(st_editingDidBegin, EditingDidBegin)
ST_UICONTROL_EVENT(st_editingChanged, EditingChanged)
ST_UICONTROL_EVENT(st_editingDidEnd, EditingDidEnd)
ST_UICONTROL_EVENT(st_editingDidEndOnExit, EditingDidEndOnExit)

//- (void)touchUpInside:(void (^)(void))eventBlock {
//   objc_setAssociatedObject(self, @selector(touchUpInside:, eventBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
//  [self addTarget:self action:@selector(touchUpInsideAction:)
//  forControlEvents:UIControlEventTouchUpInside];
//}
//- (void)touchUpInsideAction:(id)sender {
//  void (^block)() = objc_getAssociatedObject(self, @selector(touchUpInsideAction:));
//  if (block) {
//    block();
//  }
//}

@end
